package com.aqgj.common.web;

import com.aqgj.Organization.dao.OrganizationDao;
import com.aqgj.User.bean.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


import com.aqgj.User.service.UserManager;
import com.aqgj.UserRole.service.UserRoleManager;
import com.aqgj.shiro.ShiroUser;
import com.aqgj.shiro.UsernamePasswordLoginTypeToken;
import com.aqgj.util.GenericsUtils;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录控制器.
 */
@Controller
@RequestMapping("index")
public class IndexController {

    private static final Logger log = LogManager.getLogger(IndexController.class);
    @Autowired
    private UserManager userManager;
    @Autowired
    private ZtcTransportManager ztcTransportManager;
    @Autowired
    private UserRoleManager userRoleManager;
    @Autowired
    private OrganizationDao organizationDao;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginForm(Model model) {
        model.addAttribute("user", new User());
        return "redirect:/index.html";
    }

    /**
     * 用户登录.
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public HashMap<String, Object> login(User user) {
        log.info("======用户开始登录:" + user.getAccount() + " ======");
        if (GenericsUtils.isEmpty(user.getAccount())) {
            return JsonWrapper.failureWrapperMsg("用户名不能为空！");
        }
        if (GenericsUtils.isEmpty(user.getPassword())) {
            return JsonWrapper.failureWrapperMsg("密码不能为空！");
        }
        User user1 = userManager.findUniqueBy("account", user.getAccount());
        Integer cType=6;
        if (user1 != null) {
            ZtcTransport ztcTransport = ztcTransportManager.get(user1.getTransportId());
            if(ztcTransport!=null) {
                cType=ztcTransport.getType();
                if (ztcTransport.getStatus() == 1) {
                    return JsonWrapper.failureWrapperMsg("请等待审核！");
                }
                if (ztcTransport.getStatus() == 2) {
                    return JsonWrapper.failureWrapperMsg("未通过审核," + ztcTransport.getExamineRemark());
                }
            }else{
                return JsonWrapper.failureWrapperMsg("该账户不允许登录！");
            }
        }
        if (SecurityUtils.getSubject().getSession() != null) {
            SecurityUtils.getSubject().logout();
        }
        String info = loginUser(user);
        if (!"isLogin".equals(info)) {
            log.info("=============登录失败: " + info + "============");
            return JsonWrapper.failureWrapperMsg(info);
        }
        // 读取用户的url和角色
        Map<String, Set<String>> resourceMap = userRoleManager.selectResourceMapByUserId(user1.getId());
        Set<String> urls = resourceMap.get("urls");
        Set<String> roles = resourceMap.get("roles");
        ShiroUser shiroUser = new ShiroUser(user1.getId(), user1.getAccount(), user1.getName(),cType, urls);
        shiroUser.setRoles(roles);
        log.info("=============登录成功:============ ");
        return JsonWrapper.successWrapper(shiroUser);
    }

    /**
     * 登出.
     *
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public HashMap<String, Object> logout() {
        SecurityUtils.getSubject().logout();
        log.info("=============退出登录============");
        return JsonWrapper.successWrapper("退出登录成功");
    }

    /**
     * 登录验证.
     *
     * @return 登录信息.
     */
    private String loginUser(User user) {
        if (StringUtils.isBlank(user.getAccount())) {
            return "用户名不能为空";
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return "密码不能为空";
        }
        Subject users = SecurityUtils.getSubject();
        UsernamePasswordLoginTypeToken token = new UsernamePasswordLoginTypeToken(user.getAccount(),user.getPassword(),false);

        try {
            users.login(token);
            //登陆成功后设置session超时时间为一个小时
            Session session= users.getSession();
            session.setAttribute("userInfo",userManager.findUniqueBy("account", user.getAccount()));
            session.setTimeout(60*60*1000);
            return "isLogin";
        } catch (UnknownAccountException e) {
            return "账号不存在";
        } catch (DisabledAccountException e) {
            return "该账号已被禁用";
        } catch (IncorrectCredentialsException e) {
            return "密码错误";
        }catch (ExcessiveAttemptsException e) {
            return e.getMessage();
        } catch (Exception e) {
            return "内部错误，请重新尝试";
        }
    }

}
